# frozen_string_literal: true

class UpdateSetHasIssuesOnVulnerabilityReadsFunction < Gitlab::Database::Migration[2.3]
  milestone '18.6'

  def up
    execute <<~SQL
      CREATE OR REPLACE FUNCTION set_has_issues_on_vulnerability_reads() RETURNS trigger
        LANGUAGE plpgsql
        AS $$
      BEGIN
        IF (SELECT current_setting('vulnerability_management.dont_execute_db_trigger', true) = 'true') THEN
          RETURN NULL;
        END IF;

        UPDATE
          vulnerability_reads
        SET
          has_issues = true
        WHERE
          vulnerability_id = NEW.vulnerability_id AND has_issues IS FALSE;
        RETURN NULL;
      END
      $$;
    SQL
  end

  def down
    execute <<~SQL
      CREATE OR REPLACE FUNCTION set_has_issues_on_vulnerability_reads() RETURNS trigger
        LANGUAGE plpgsql
        AS $$
      BEGIN
      UPDATE
        vulnerability_reads
      SET
        has_issues = true
      WHERE
        vulnerability_id = NEW.vulnerability_id AND has_issues IS FALSE;
      RETURN NULL;
      END
      $$;
    SQL
  end
end
